package cn.harry.modular.oss.controller;

import cn.harry.common.api.R;
import cn.harry.modular.oss.service.OssService;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * 文件接口
 *
 * @author harry
 * @公众号 Harry技术
 */
@Tag(name = "文件接口")
@RestController
@RequestMapping("/oss")
@RequiredArgsConstructor
public class OssController {
    private final OssService ossService;

    @PostMapping
    @Operation(summary = "文件上传")
    public R<String> uploadFile(@Parameter(name = "file", description = "表单文件对象", required = true, in = ParameterIn.DEFAULT, schema = @Schema(name = "file", format = "binary"))
                                    @RequestPart(value = "file") MultipartFile file) {
        return R.success(ossService.uploadFile(file));
    }

    @DeleteMapping
    @Operation(summary = "文件删除")
    @SneakyThrows
    public R<?> deleteFile(@Parameter(description = "文件路径") @RequestParam String filePath) {
        boolean result = ossService.deleteFile(filePath);
        return R.success(result);
    }

    @PostMapping("/editor")
    @Operation(summary = "editor文件上传")
    public Map<String, Object> editorUpload(@Parameter(name = "file", description = "表单文件对象", required = true, in = ParameterIn.DEFAULT, schema = @Schema(name = "file", format = "binary"))
                                            @RequestPart(value = "file") MultipartFile file) {

        String url = ossService.uploadFile(file);
        JSONObject json = new JSONObject();
        json.set("url", url);
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(json);

        return Map.of("errno", 0, "data", jsonArray);
    }
}
